package com.fanxj.service.impl;

import com.fanxj.Utils.DynastyConverter;
import com.fanxj.Utils.OllamaService;
import com.fanxj.domain.Params;
import com.fanxj.domain.Relic;
import com.fanxj.domain.SearchParams;
import com.fanxj.mapper.CulturalRelicMapper;
import com.fanxj.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@Service("SearchService")
public class SearchServiceImpl implements SearchService {
    @Autowired
    private OllamaService ollamaService;

    @Autowired
    private CulturalRelicMapper relicMapper;

    @Override
    public List<Relic> smartSearch(String smartSearchValue) throws IOException {
        // Step 1: 大模型解析
        Map<String, Object> params = ollamaService.parseQuery(smartSearchValue);

        // Step 2: 参数转换
        SearchParams searchParams = convertParams(params);
        System.out.println(searchParams);
        // Step 3: 执行查询
        return relicMapper.complexSearch(searchParams);
    }

    private SearchParams convertParams(Map<String, Object> rawParams) {
        SearchParams params = new SearchParams();
        // 朝代转换
        if(((String) rawParams.get("decadeType")).equals("未知"))
            params.setDecadeType(null); // 如果大模型未返回 decadeType，设置为 null
        else{
            String decadeType = DynastyConverter.convert((String) rawParams.get("decadeType"));
            params.setDecadeType(decadeType);
        }

        // 分类转换（基于提供的分类表）
        if(((String) rawParams.get("groupType")).equals("未知"))
            params.setGroupType(null);
        else
            params.setGroupType((String) rawParams.get("groupType"));

        // 地域转换
        if(((String) rawParams.get("localType")).equals("未知"))
            params.setLocalType(null);
        else
            params.setLocalType((String) rawParams.get("localType"));


        // 纹样特征
        if (rawParams.containsKey("pattern")) {
            Object pattern = rawParams.get("pattern");
            if (pattern instanceof List) {
                params.setPattern((List<String>) pattern);
            } else {
                params.setPattern(Collections.singletonList((String) pattern));
            }
        } else {
            params.setPattern(null); // 如果大模型未返回 pattern，设置为 null
        }

        System.out.println(params); // 打印参数，方便调试
        return params;
    }
}
